package org.mcjug;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;

import org.mcjug.model.OAuthRequestTokenTask;
import org.mcjug.model.RetrieveAccessTokenTask;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

public class OauthActivity extends Activity {
	private CommonsHttpOAuthConsumer consumer;
	private CommonsHttpOAuthProvider provider;
	public static final String CONSUMER_KEY = "08LuAfmwCrfQsXUcr6R5w";
	public static final String CONSUMER_SECRET = "5nTsOzbVvxpSkb51VX3TYlxF7mwYC7fiRxKbLc7E1MU";
	public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow";
	public static final String CALLBACK_URL = OAUTH_CALLBACK_SCHEME
			+ "://callback";
	final String TAG = getClass().getName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
		provider = new CommonsHttpOAuthProvider(
				"https://api.twitter.com/oauth/request_token",
				"https://api.twitter.com/oauth/access_token",
				"https://api.twitter.com/oauth/authorize");

		new OAuthRequestTokenTask(this, consumer, provider).execute();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		final Uri uri = intent.getData();
		if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
			Log.i(TAG, "Callback received : " + uri);
			Log.i(TAG, "Retrieving Access Token");
			new RetrieveAccessTokenTask(this, consumer, provider, prefs)
					.execute(uri);
			finish();
		}
	}

}
